package com.qzl.client.server;

import com.qzl.common.common.RespConstant;
import com.qzl.common.netty.config.ChatConfig;
import com.qzl.common.netty.message.Message;
import com.qzl.common.netty.model.UserModel;
import com.qzl.common.netty.protocol.MessageCodec;
import com.qzl.common.netty.utis.ChatUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.*;

@Slf4j
public class NettyClient {
    private static final BlockingQueue<Message> queue = new LinkedBlockingQueue<>();

    public static void main(String[] args) throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
//                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new MessageCodec());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<Message>() {
                            @Override
                            public void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
                                log.info("收到服务端消息：{}", msg);
                                String title = String.format("收到来自：%s 的消息，内容：%s", StringUtils.isBlank(msg.getFrom()) ? "系统" : msg.getFrom(), msg.getContent());
                                System.out.println(title);
                                queue.add(msg);
                            }

                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                log.info("连接成功");
                                new Thread(() -> {
                                    Scanner scanner = new Scanner(System.in);
                                    while (true) {
                                        // 模拟登录，有客户端的话也可以先在页面登录，然后拿到token，在netty直接模拟登陆，然后发起聊天
                                        System.out.println("请输入用户名：");
                                        String username = scanner.nextLine();
                                        System.out.println("请输入密码：");
                                        String password = scanner.nextLine();
                                        Message message = new Message();
                                        message.setMessageType((int) ChatConfig.LOGIN_MESSAGE);
                                        message.setSequenceId(ChatUtils.getSequenceId());
                                        UserModel userModel = new UserModel(username, password);
                                        message.setUserModel(userModel);
                                        ctx.writeAndFlush(message);
                                        // 阻塞等待服务端返回消息
                                        try {
                                            Message loginResMsg = queue.take();
                                            log.info("服务端返回登录消息：{}", loginResMsg);
                                            if (loginResMsg.getContent().contains(RespConstant.USERNAME_PASSWORD_ERROR.getMessage())) {
                                                ctx.channel().close();
                                                return;
                                            } else {
                                                System.out.println("登录成功");
                                            }
                                            while (true) {
                                                System.out.println("==================================");
                                                System.out.println("send [username] [content]");
                                                System.out.println("gsend [group name] [content]");
                                                System.out.println("gcreate [group name] [m1,m2,m3...]");
                                                System.out.println("gmembers [group name]");
                                                System.out.println("gjoin [group name]");
                                                System.out.println("gquit [group name]");
                                                System.out.println("quit");
                                                System.out.println("==================================");
                                                System.out.println("请输入要发送的消息：");
                                                String messageStr = scanner.nextLine();
                                                String[] split = messageStr.split(" ");
                                                Message sendMessage = new Message();
                                                switch (split[0]) {
                                                    case "send":
                                                        sendMessage.setTo(split[1]);
                                                        sendMessage.setContent(split[2]);
                                                        sendMessage.setMessageType((int) ChatConfig.CHAT_MESSAGE);
                                                        sendMessage.setSequenceId(ChatUtils.getSequenceId());
                                                        sendMessage.setToken(loginResMsg.getToken());
                                                        ctx.writeAndFlush(sendMessage);
                                                        break;
                                                }

                                            }

                                        } catch (Exception e) {
                                            log.error("等待服务端响应失败", e);
                                        }
                                    }
                                }).start();
                            }
                        });

                    }
                }).connect("127.0.0.1", 8848)
                .sync().channel();
        channel.closeFuture().sync();
    }
}
